import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:im_demo/app/constant/storage_key.dart';
import 'package:im_demo/core/network/http_util.dart';
import 'package:im_demo/utils/my_http_overrides.dart';

import 'app/routes/app_pages.dart';

void main() {
  if (kDebugMode) {
    HttpOverrides.global = MyHttpOverrides();
  }

  GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

  _init();

  runApp(
    GetMaterialApp(
      title: "Application",
      initialRoute: AppPages.INITIAL,
      getPages: AppPages.routes,
      theme: ThemeData(useMaterial3: true),
      builder: (BuildContext context, Widget? child) {
        FToast().init(context);
        return EasyLoading.init()(context, child);
      },
      navigatorKey: navigatorKey,
    ),
  );
}

void _init() async {
  await GetStorage.init();
  await _initProxySetting();
  _initHttp();
}

Future<void> _initProxySetting() async {
  bool enableProxy = GetStorage().read(StorageKey.ENABLE_PROXY) ?? false;

  await GetStorage().remove(StorageKey.PROXY_ADDRESS);

  final String defaultProxyAddress = '172.31.128.1:10000';
  final String cacheAddress = GetStorage().read(StorageKey.PROXY_ADDRESS) ?? '';
  final String proxyAddress =
      cacheAddress.isEmpty ? defaultProxyAddress : cacheAddress;

  await GetStorage().write(StorageKey.PROXY_ADDRESS, proxyAddress);
}

_initHttp() {
  final baseUrl = 'http://192.168.1.100:8088';
  HttpUtil().init(defaultBaseUrl: baseUrl, debugMode: true);
}
